<template>
  <div>
    <Loading :loading="isLoading" fixed></Loading>
    <van-skeleton avatar title v-for="item in 10" v-if="showSkeleton" />

    <div class="suggest wrap">
      <div class="list-box" v-if="suggestList.length != 0 && !showSkeleton">
        <div class="list" v-for="item in suggestList" :key="item.id" @click="search(item.name)">
          <van-icon name="search" />
          <p class="van-ellipsis">{{ item.name }}</p>
        </div>
      </div>
      <van-empty image="search" v-else-if="suggestList.length == 0 && isLoading == false" description="暂无相关内容" />
    </div>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, watch } from 'vue'
import { getSearchSuggest } from '@/request/api/musicApi'
import Loading from '@/components/common/Loading.vue'

const emit = defineEmits(['isShow', 'search'])
let isLoading = ref(true);

// 获取搜索建议
let suggestList = ref([]);
let suggestVal = ref('');
let showSkeleton = ref(true)
const searchSuggest = async (keywords) => {
  suggestVal.value = keywords;
  showSkeleton.value = true;
  // 搜索时先重置数据
  resetData();
  await getSearchSuggest({ keywords: keywords }).then(data => {
    isLoading.value = false;
    suggestList.value = [...data.result.songs || '', ...data.result.artists || '', ...data.result.albums || '', ...data.result.playlists || ''];

    showSkeleton.value = false;
  })
}

// 控制返回按钮
watch(suggestVal, (newval, oldval) => {
  newval != '' ? emit('isShow') : emit('isShow', false);
})

const search = (data) => {
  emit('search', data);
  resetData()
}

// 重置数据
const resetData = () => {
  suggestList.value = [];
  isLoading.value = true;
}

defineExpose({
  searchSuggest,
  resetData
})
</script>
  
<style lang='less' scoped>
.wrap {
  padding-left: 20px;
  box-sizing: border-box;
}

.suggest {
  display: flex;
  flex-wrap: wrap;
  background-color: #FFF;

  .list-box {
    width: 100%;
  }

  .list {
    width: 100%;
    display: flex;
    align-items: center;
    height: 100px;
    line-height: 100px;
    font-size: 35px;

    p {
      width: 100%;
      font-size: 30px;
      border-bottom: 1px solid var(--van-border-color);
    }

    &:last-child {
      p {
        border-bottom: none;
      }
    }

    .van-icon {
      margin-right: 20px;
    }
  }
}

.van-empty {
  width: 100%;
}

.van-skeleton {
  margin-bottom: 30px;

  .van-skeleton__title {
    width: 100%;
  }
}
</style>